import os
import re
import subprocess
from datetime import datetime
from pathlib import Path
from openpyxl import Workbook
import sys

import tkinter as tk
from tkinter import ttk, filedialog, messagebox


# 检查文档中格式错误情况

def main(git_path):
    print("main")
    if not os.path.exists(git_path):
        raise FileNotFoundError(f"文档仓路径不存在：{git_path}")

    now = datetime.now()
    # 获取 exe 所在目录（兼容打包前后两种环境）
    if getattr(sys, 'frozen', False):
        current_dir = os.path.dirname(sys.executable)  # 打包后 exe 路径
    else:
        current_dir = os.path.dirname(os.path.abspath(__file__))  # 开发环境路径

    # 拼接 Excel 文件路径，得到输出信息位置
    excel_path = os.path.join(current_dir, 'docs-md-style-check-' + now.strftime("%Y-%m-%d-%H-%M-%S") + '.xlsx')

    md_info = MdInfo(git_path, excel_path)
    md_info.operation()


# 处理当前md中责任田信息
class MdInfo:

    def __init__(self, git_path, excel_path):
        '''
            @param git_path: docs 仓路径
            @param excel_path: 责任田文档输出路径
        '''
        self.git_path = git_path
        self.excel_path = excel_path

    # 读取信息并处理
    def operation(self):
        # 加载工作簿
        wb = Workbook()
        # 激活工作表
        sheet = wb.active
        sheet.title = '文档目录及责任人'
        if not os.path.exists(self.git_path):
            sheet['A1'] = '本地代码仓路径错误'
            wb.save(self.excel_path)
            return
        sheet.append(
            ["文档路径", '错误行号', '错误类型', '处理结果'])
        self.get_md_info(sheet)
        wb.save(self.excel_path)

    def get_md_info(self, sheet):
        # 判断当前路径是文件还是文件夹，是文件的话直接处理
        if os.path.isdir(self.git_path):
            directory_path = Path(self.git_path)
            for file_path in directory_path.rglob('*.md'):
                self.get_md_owner(file_path, sheet)
        elif os.path.isfile(self.git_path):
            self.get_md_owner(self.git_path, sheet)

    # 获取文档相关信息并输出到Excel
    def get_md_owner(self, file_path, sheet):
        md_info_line = ['', '', '', '']
        md_info_line[0] = str(file_path)
        print(file_path)
        command = ["npx", "markdownlint-cli2"]
        current_path = os.getcwd()
        parent_dir = os.path.dirname(current_path)
        config_path = os.path.join(parent_dir, r'.markdownlint.jsonc')
        # print(config_path)
        command.extend(["--config", config_path])
        command.append(file_path)
        # 运行命令行
        result = subprocess.run(command, capture_output=True, text=True, check=False, shell=True)
        # returncode = 1，表示文档中存在格式错误
        if result.returncode == 1:
            lines = result.stderr.splitlines()
            for line in lines:
                error_line_number, error_type = parse_md_style_error(line)
                # 添加信息
                md_info_line[1] = error_line_number
                if error_type == '029':
                    md_info_line[2] = "序列号格式异常"
                if error_type == '046':
                    md_info_line[2] = "代码块格式错误"
                sheet.append(md_info_line)

        # 打开链接对应的文档
        with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
            data = f.read()
            pattern = re.compile(r' *```[\s\S]+?```', re.DOTALL)
            matches = list(pattern.finditer(data))
            for match in matches:
                start_position = match.start(0)
                start_line_number = data.count('\n', 0, start_position) + 1
                code_datum = match.group()
                lines = code_datum.splitlines()
                code_space_count_min = len(lines[0]) - len(lines[0].lstrip(" "))
                # 统计检测到了第几行
                count = 0
                for line in lines:
                    # print("code line:" + line)
                    code_space_count = len(line) - len(line.lstrip(" "))
                    # print("code line count:" + str(code_space_count))
                    if code_space_count < code_space_count_min:
                        # print(f'当前文档中的第{start_line_number + count}行缩进出现问题')
                        md_info_line[1] = str(start_line_number + count)
                        md_info_line[2] = "代码块缩进异常"
                        sheet.append(md_info_line)
                    count += 1



def parse_md_style_error(line):
    # print(line)
    error_line_reg = re.compile(r'\.md:(\d+)')
    error_line_number = re.search(error_line_reg, line).group(1)
    error_type_regex = re.compile(r'MD(\d+)')
    error_type = re.search(error_type_regex, line).group(1)
    # print(error_line_number)
    # print(error_type)
    return error_line_number, error_type

if __name__ == '__main__':
    # git_path = 'D:\project\docs\zh-cn\\application-dev\\'
    git_path = 'D:\project\gitCode\docs\zh-cn\\application-dev\\reference\\apis-arkweb\\arkts-basic-components-web-HttpAuthHandler.md'
    # git_path = 'D:\project\gitCode\docs\zh-cn\\application-dev'
    main(git_path)
    # root = tk.Tk()
    # app = MdCheckApp(root)
    # root.mainloop()
